<script setup lang="ts">
import { Upload, UploadFilled } from "@element-plus/icons-vue";
import { onMounted, reactive, ref } from "vue";
import {
  uploadVppFile,
  getVppFile,
  previewVppFile,
  downVppFile,
  delVppFile
} from "@/api/vppFile";
import { ElNotification, ElLoading } from "element-plus";
import { downloadFile, parseTime } from "@/utils";
const props = defineProps({
  activeVppUserId: {
    type: String
  },
  handleStatus: {
    type: String,
    default: "add"
  },
  moduleType: {
    type: String,
    default: "vpp_user_info"
  }
});
const files = reactive({
  data: []
});
const fileChange = e => {
  files.data.push(e);
};
const fileRemove = e => {
  let index = files.data.findIndex(i => i.uid === e.uid);
  files.data.splice(index, 1);
};
const dialogShow = ref(false);
const uploadShow = () => {
  dialogShow.value = true;
};
const handleClose = d => {
  uploadRef.value.clearFiles();
  files.data = [];
  d();
};
const uploadRef = ref(null);
const cancel = () => {
  uploadRef.value.clearFiles();
  files.data = [];
  dialogShow.value = false;
};
const tableData = reactive({
  data: []
});
const getList = async () => {
  let res = await getVppFile({
    pid: props.activeVppUserId,
    source: props.moduleType
  });
  // console.log(res, "--");
  tableData.data = res.content;
};
const uploadFileFunc = data => {
  return new Promise((resolve, reject) => {
    uploadVppFile(data.data)
      .then(res => {
        ElNotification({
          title: "系统提示",
          message: data.name + "上传成功",
          type: "success"
        });
        resolve(res);
      })
      .catch(e => {
        ElNotification({
          title: "系统提示",
          message: data.name + "上传失败",
          type: "error"
        });
        reject(e);
      });
  });
};
const upLoading = ref(false);
const submit = async () => {
  if (files.data.length) {
    upLoading.value = true;
    let allData = [];
    files.data.forEach((i, index) => {
      let item = {
        data: null,
        name: i.name
      };
      let data = new FormData();
      data.append("multipartfile", i.raw);
      data.append("pid", props.activeVppUserId);
      data.append("source", props.moduleType);
      data.append("type", 1);
      data.append("sort", index + 1);
      data.append("encryption", "NO");
      item.data = data;
      allData.push(item);
    });
    try {
      await Promise.all(allData.map(i => uploadFileFunc(i)));
    } catch (e) {
      console.error(e, "error");
      upLoading.value = false;
    }
    upLoading.value = false;
    cancel();
    getList();
  } else {
    cancel();
  }
};
const preview = async row => {
  const loading = ElLoading.service({
    lock: true,
    text: "预览中...",
    background: "rgba(0, 0, 0, 0.7)"
  });
  let obj = await previewVppFile({ id: row.id });
  window.open(obj);
  // let last = "";
  // if (obj.type.indexOf("/") > -1) {
  //   let list = obj.type.split("/");
  //   last = list[list.length - 1];
  // }
  // downloadFile(obj, "预览数据", last, true);
  loading.close();
};
const downFile = async row => {
  const loading = ElLoading.service({
    lock: true,
    text: "下载中...",
    background: "rgba(0, 0, 0, 0.7)"
  });
  let obj = await downVppFile(row.id);
  let last = "";
  let name = "";
  if (row.name.indexOf(".") > -1) {
    let names = row.name.split(".");
    last = names[names.length - 1];
    names.splice(names.length - 1, 1);
    name = names.join("");
  } else {
    name = row.name;
    last = "";
  }
  downloadFile(obj, name, last, true);
  loading.close();
};
const delConfirm = async row => {
  await delVppFile(row.id);
  ElNotification({
    title: "系统提示",
    message: "删除成功",
    type: "success"
  });
  getList();
};
onMounted(() => {
  if (props.activeVppUserId && props.activeVppUserId !== "null") {
    getList();
  }
});
</script>

<template>
  <div class="w-full main h-[calc(100%-29px)]">
    <div class="w-full">
      <div v-if="handleStatus !== 'look'">
        <el-button type="primary" :icon="Upload" @click="uploadShow"
          >上传附件</el-button
        >
      </div>
      <el-table :data="tableData.data">
        <el-table-column prop="name" label="文件名称" />
        <!--        <el-table-column prop="url" label="预览地址" />-->
        <el-table-column prop="encryption" label="是否加密" />
        <!--        <el-table-column prop="source" label="源" />-->
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column fixed="right" width="200px">
          <template #default="scope">
            <el-button
              size="small"
              text
              type="primary"
              @click="preview(scope.row)"
              >预览</el-button
            >
            <el-button
              size="small"
              text
              type="primary"
              @click="downFile(scope.row)"
              >下载</el-button
            >
            <el-popconfirm
              v-if="handleStatus !== 'look'"
              width="200px"
              title="确定删除本条数据吗？"
              @confirm="delConfirm(scope.row)"
            >
              <template #reference>
                <el-button size="small" text>删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      v-model="dialogShow"
      title="上传附件"
      width="30%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <div v-loading="upLoading">
        <el-upload
          ref="uploadRef"
          drag
          action="/"
          multiple
          :limit="9"
          :auto-upload="false"
          :on-change="fileChange"
          :on-remove="fileRemove"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">拖拽或点击上传</div>
          <!--          <template #tip>-->
          <!--            <div class="el-upload__tip">-->
          <!--              jpg/png files with a size less than 500kb-->
          <!--            </div>-->
          <!--          </template>-->
        </el-upload>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button :loading="upLoading" type="primary" @click="submit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
